import { queryCouponGoodsList } from '@/services/coupon.service';
import { useDeepCompareEffect } from 'ahooks';
import { Col, Modal, Row, Space, Tag } from 'antd';
import type { FC } from 'react';
import { useState } from 'react';
import DebounceSelect from '../DebounceSelect';
import styles from './index.less';

type TProps = {
  title: string;
  visible: boolean;
  onSubmit: TAnyFunction;
  onCancel: TAnyFunction;
  data: TIdNameData[];
  goodType: any;
};

const PickerModal: FC<TProps> = (props) => {
  const { title, visible, onSubmit, onCancel, data, goodType } = props;
  const [showValue, setShowValue] = useState<any[]>([]);
  const [showOotions, setShowOotions] = useState<any[]>([]);

  // console.log('1010101010子', goodType, showValue, showOotions);

  const handleSubmit = () => {
    // onSubmit &&
    //   onSubmit(
    //     showValue.map((o) => ({
    //       name: o.label,
    //       id: o.value,
    //       goodsNames: o.goodsNames || [],
    //     })),
    //   );
    onSubmit &&
      onSubmit(
        showOotions.map((o) => ({
          name: o.name,
          id: o.id,
          goodsNames: o.goodsNames || [],
          linkIds: o?.linkIds || [],
        })),
      );
  };

  const handleChange = (newValue: any, options: any) => {
    // console.log('oooooooo', options, newValue);
    setShowValue(newValue);
    // 数组筛选去重
    const resList: any = [];
    const concatList = options.concat(showOotions);
    for (const item of concatList) {
      if (item && JSON.stringify(item) !== '{}') {
        let flag = true;
        for (const val of resList) {
          if (item.id === val.id) {
            flag = false;
          }
        }
        if (flag) {
          resList.push(item);
        }
      }
    }
    setShowOotions(resList);
  };

  const handleTagClose = (id: string | number) => {
    const retValue = [...showValue];
    const index = showValue.findIndex((o) => o.value === id);
    retValue.splice(index, 1);
    setShowValue(retValue);
    const retOptionValue = [...showOotions];
    const optionIndex = showOotions.findIndex((o) => o.value === id);
    retOptionValue.splice(optionIndex, 1);
    setShowOotions(retOptionValue);
  };

  useDeepCompareEffect(() => {
    setShowValue(
      data.map((o) => ({
        label: o.name,
        value: o.id,
        goodsNames: o.goodsNames || [],
        linkIds: o?.linkIds || [],
      })),
    );
    setShowOotions(
      data.map((o) => ({
        name: o.name,
        id: o.id,
        goodsNames: o.goodsNames || [],
        linkIds: o?.linkIds || [],
      })),
    );
  }, [data]);

  const fetchData = async (val: any): Promise<TIdNameData[]> => {
    const res = await queryCouponGoodsList({ search: val, type: goodType });
    // console.log('resssss', res);
    if (res.code === 0) {
      const list: any = [];
      res.data.map((item: any) => {
        if (goodType === 1 || goodType === 2) {
          list.push({
            id: item.categoryCode,
            name: `${item.category}（${item.categoryCode}）`,
            goodsNames: item.goodsNames,
            linkIds: item.linkIds,
          });
        } else {
          list.push({
            id: item.linkId,
            name: `${item.goodsName}（${item.linkId}）`,
            goodsNames: item.goodsNames,
          });
        }
      });
      return list;
    } else {
      return [];
    }
  };

  return (
    <Modal
      title={`选择${title}`}
      open={visible}
      width={600}
      onCancel={onCancel}
      onOk={handleSubmit}
    >
      <div className={styles.choseContainer}>
        <Row>
          <Col span={24}>
            <DebounceSelect
              mode="multiple"
              value={showValue}
              fieldNames={{
                label: 'name',
                value: 'id',
              }}
              maxTagCount="responsive"
              placeholder={`请输入${title}`}
              fetchOptions={fetchData as any}
              onChange={handleChange}
              style={{ width: '300px' }}
            />
          </Col>

          <Col span={24} className="mt-16">
            <Space wrap>
              {showValue.map((o) => (
                <Tag
                  key={o.value}
                  closable
                  onClose={() => {
                    handleTagClose(o.value);
                  }}
                >
                  <span>商品ID：{o.value} </span>
                  <span>
                    {' '}
                    商品名称：{o.label.includes('（') ? o.label.split('（')[0] : o.label}
                  </span>
                </Tag>
              ))}
            </Space>
          </Col>
        </Row>
      </div>
    </Modal>
  );
};

export default PickerModal;
